package com.e.takeaway;

import static com.e.takeaway.R.drawable.calcu2;
import static com.e.takeaway.R.drawable.calculate;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.e.takeaway.adapter.FoodAdapter;
import com.e.takeaway.po.Food;
import com.e.takeaway.po.MerChant;
import com.e.takeaway.util.MyRetrofit;
import com.e.takeaway.service.RequestService;
import com.squareup.picasso.Picasso;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class DetailActivity extends AppCompatActivity {
    private ImageView img_top,img_back_1;
    private static ImageView img_shop;
    private TextView tv_mername,tv_score,tv_sale,tv_time;
    private static TextView tv_sum,tv_jiesaun;
    private ListView listView1;
    private MerChant merChant;
    private List<Food> foods;
    static private List<Food> myfoods;
    private FoodAdapter foodAdapter;
    private static RelativeLayout layout;
    static Drawable drawable1;
    static Drawable drawable2;
    private int Id;
    private static BigDecimal bigprice = new BigDecimal(0.00);



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);
        getSupportActionBar().hide();
        drawable1 = DetailActivity.this.getDrawable(calcu2);
        drawable2 = DetailActivity.this.getDrawable(calculate);

        InitView();
        setData();
        requestData(Id);
        back();

    }
    public static Handler handler = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case 100:
                    bigprice = BigDecimal.valueOf(0.00);
                    layout.setBackground(drawable1);
                    img_shop.setImageResource(R.drawable.gouwuche1);
                    Food food =(Food) msg.getData().getSerializable("food");
                    tv_jiesaun.setText("结算");
                    tv_jiesaun.setClickable(true);
                    if (myfoods == null || myfoods.isEmpty()){
                        myfoods = new ArrayList<>();
                        food.setSum(food.getFoodPrice().multiply(new BigDecimal(food.getNumber().toString())));
                        myfoods.add(food);
                        bigprice = bigprice.add(food.getSum());
                    }else{
                        // 修改数量
                        boolean flag = true;
                        for (int i = 0; i < myfoods.size(); i++) {
                            if(myfoods.get(i).getFoodId().equals(food.getFoodId())){
                                myfoods.get(i).setNumber(food.getNumber());
                                myfoods.get(i).setSum(food.getFoodPrice().multiply(new BigDecimal(food.getNumber().toString())));
                                flag = false;
                                break;
                            }
                        }

                        if (flag){
                            food.setSum(food.getFoodPrice().multiply(new BigDecimal(food.getNumber().toString())));
                            myfoods.add(food);
                        }

                        for (int i=0; i<myfoods.size(); i++){
                            bigprice = bigprice.add(myfoods.get(i).getSum());
                        }

                    }
                    System.out.println(myfoods);
                    tv_sum.setText(bigprice.toString());
                    break;
                case 200:
                    bigprice = BigDecimal.valueOf(0.00);
                    Integer foodId = msg.getData().getInt("food_id");
                    myfoods.removeIf(f -> f.getFoodId().equals(foodId));
                    if(myfoods.size() == 0){
                        layout.setBackground(drawable2);
                        img_shop.setImageResource(R.drawable.gouwuche);
                        bigprice = BigDecimal.valueOf(0.00);
                        tv_jiesaun.setText("未选购商品");
                        tv_jiesaun.setClickable(false);
                    }
                    for(int i=0;i<myfoods.size();i++){
                        bigprice = bigprice.add(myfoods.get(i).getSum());
                    }
                    System.out.println(myfoods.toString());
                    tv_sum.setText(bigprice.toString());
                    break;
                case 300:
                    bigprice = BigDecimal.valueOf(0.00);
                    Integer foodId1 = msg.getData().getInt("food_id");
                    for (int i = 0; i < myfoods.size(); i++) {
                        if(myfoods.get(i).getFoodId().equals(foodId1)){
                            myfoods.get(i).setSum( myfoods.get(i).getFoodPrice().multiply(new BigDecimal( myfoods.get(i).getNumber().toString())));
                        }
                        bigprice = bigprice.add(myfoods.get(i).getSum());
                    }
                    System.out.println(myfoods.toString());
                    tv_sum.setText(bigprice.toString());
                    break;
                default:
                    throw new IllegalStateException("Unexpected value: " + msg.what);
            }
        }
    };


    private void InitView(){
        tv_sum = findViewById(R.id.detail_sum);
        img_top = (ImageView) findViewById(R.id.detail_img);
        tv_mername= (TextView) findViewById(R.id.tv_detailname);
        tv_score = (TextView) findViewById(R.id.detail_score);
        tv_sale = (TextView) findViewById(R.id.detail_sole);
        tv_time = (TextView) findViewById(R.id.detail_take);
        listView1 = (ListView) findViewById(R.id.detail_list);
        img_shop =(ImageView)findViewById(R.id.car_img);
        img_back_1=(ImageView)findViewById(R.id.back_1);
        layout = (RelativeLayout)findViewById(R.id.car);
        tv_jiesaun = (TextView) findViewById(R.id.detail_jiesuan);
        tv_jiesaun.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(DetailActivity.this,PayActivity.class);
                Bundle b = new Bundle();
                ArrayList list = new ArrayList();
                list.add(myfoods);
                b.putParcelableArrayList("myfood",list);
                b.putString("shopimg",merChant.getMerImg());
                b.putString("shopname",tv_mername.getText().toString());
                b.putString("time",tv_time.getText().toString());
                intent.putExtras(b);
                startActivity(intent);
            }
        });
    }

    public void setData(){
        Bundle b= getIntent().getExtras();
        merChant = (MerChant) b.getSerializable("mer");
        Id = merChant.getMerId();
        Picasso.with(this)
                .load(merChant.getMerImg())
                .placeholder(img_top.getDrawable())
                .error(R.drawable.lunbo1)
                .into(img_top);
        tv_mername.setText(merChant.getMerName());
        tv_score.setText(""+merChant.getMerScore());
        tv_sale.setText("月售"+merChant.getMerSale());
        tv_time.setText("配送约"+merChant.getMerTime()+"分钟");
    }

    private void requestData(int id) {
        Retrofit retrofit = MyRetrofit.getRetrofit();
        RequestService request = retrofit.create(RequestService.class);
        Call<List<Food>> call = request.getFoodList(id);
        call.enqueue(new Callback<List<Food>>() {
            @Override
            public void onResponse(Call<List<Food>> call, Response<List<Food>> response) {
                foods = response.body();
                System.out.println("----------"+foods);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        foodAdapter = new FoodAdapter(DetailActivity.this,foods);
                        listView1.setAdapter(foodAdapter);

                    }
                });
            }

            @Override
            public void onFailure(Call<List<Food>> call, Throwable t) {
                System.out.println("-------------------->error");
            }
        });
    }

    public void back(){
        img_back_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (null!=myfoods || myfoods.isEmpty() || myfoods.size()!=0){
                    myfoods.clear();
                    myfoods = null;
                }
                finish();
            }
        });


    }
}